package com.fingard.dsp.bank.directbank.shie01;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.shie.openapi.dto.ResponseDto;

public class SHIE01BatPayRec extends SHIE01Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        String commandCode = p_req1988.reqHeader.commandCode;
        if ("198803".equals(commandCode)) {
            return d_198803(p_req1988);
        } else {
            return d_198801(p_req1988);
        }
    }
    /**
     *  198801 批量对外支付  一户通
     *
     * @param p_req1988
     * @return
     * @throws Exception
     */
    public RetAtsBatPayRec d_198801(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "*");
            if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
                retAts.respCode = "0";
                if(actItem == null){
                    retAts.respInfo = "未找到账号"+p_req1988.ownAct+"的批量商户配置节点";
                }else{
                    retAts.respInfo = "账号"+p_req1988.ownAct+"的商户证书文件不存在";
                }
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;

                retAts.writeRetToATS();
                return retAts;
            }

            String serviceCode = SHIE01TransType.P198801;

            Map<String, Object> bizContent = new HashMap<String, Object>();

            // 商户代码
            bizContent.put("comCode", actItem.inMerchantId);
            // 一户通账号
            bizContent.put("payeeCustId", actItem.virtualAct);
            // 机构批次号
            bizContent.put("batchNo", p_req1988.reqBatchNO);
            // 订单商品代码
            bizContent.put("productCode", getBankConfig().getMapValueByKey("productCode", "1"));
            // 总笔数
            bizContent.put("totalNum", p_req1988.totalNum);
            // 总金额
            bizContent.put("totalAmt", StringHelper.amountMultiply100(p_req1988.totalAmt));
            // 异步通知
            bizContent.put("notifyURL", actItem.notifyURL);

            JSONArray detailJsonArray = new JSONArray();

            while(p_req1988.readRecord()) {
                JSONObject detailJSONObject = new JSONObject();

                // 机构订单号
                detailJSONObject.put("orderId", p_req1988.readedDetail.askNumber);
                // 商户渠道ID
                detailJSONObject.put("accChanId", actItem.merchantId);
                // 收款银行行别
                detailJSONObject.put("bankType", p_req1988.readedDetail.recBankCode);
                // 收款银行支行名称
                detailJSONObject.put("bankName", p_req1988.readedDetail.recBankName + p_req1988.readedDetail.recBankLocation);
                // 收款方户名
                detailJSONObject.put("bankCardName", p_req1988.readedDetail.recName);
                // 收款方银行卡号
                detailJSONObject.put("bankCardNo", p_req1988.readedDetail.recAct);
                // 交易币种  填默认值：1(人民币)
                detailJSONObject.put("currenoy", "1");
                // 收款方对公对私账号类型 填默认值：2(对私)
                if ("1".equals(p_req1988.readedDetail.isPrivate)) {
                    detailJSONObject.put("pubPriv", "2");
                } else {
                    detailJSONObject.put("pubPriv", "1");
                }

                // 摘要
                String summary = p_req1988.readedDetail.memo;
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.purpose;
                }
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.useType;
                }
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.abstractATS;
                }
                detailJSONObject.put("optional", summary);

                // 交易金额
                detailJSONObject.put("amount", StringHelper.amountMultiply100(p_req1988.readedDetail.payAmount));

                detailJsonArray.add(detailJSONObject);
            }

            bizContent.put("details", detailJsonArray);

            ResponseDto responseDto = sendToSHIE(actItem, serviceCode, bizContent);

            // 解析银行返回
            String tmpRespCode = responseDto.getResponseCode();
            if ("0000".equals(tmpRespCode)) {
                JSONObject respBizContent = JSON.parseObject(responseDto.getBizContent());

                String msgCode = respBizContent.getString("msgCode");

                retAts.respCode = "0";
                retAts.respInfo = respBizContent.getString("msgInfo");
                retAts.transState = tmpRespCode + "+" + msgCode;
                retAts.payInfoCode = msgCode;
            } else {
                if ("9105".equals(tmpRespCode)) {
                    retAts.respCode = "0";
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = tmpRespCode;
                } else {
                    retAts.respCode = "-1";
                }

                retAts.respInfo = responseDto.getResponseDesc();
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }

        if(StringHelper.isNullOrEmpty(retAts.reqSeqID)){
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     *  198802 批量支付
     *
     * @param p_req1988
     * @return
     * @throws Exception
     */
    public RetAtsBatPayRec d_198803(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "*");
            if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
                retAts.respCode = "0";
                if(actItem == null){
                    retAts.respInfo = "未找到账号"+p_req1988.ownAct+"的批量商户配置节点";
                }else{
                    retAts.respInfo = "账号"+p_req1988.ownAct+"的商户证书文件不存在";
                }
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;

                retAts.writeRetToATS();
                return retAts;
            }

            String serviceCode = SHIE01TransType.P198803;

            Map<String, Object> bizContent = new HashMap<String, Object>();

            // 商户代码
            bizContent.put("comCode", actItem.inMerchantId);
            // 付款银行账号
            bizContent.put("payerAcctNo", p_req1988.ownAct);
            // 付款银行户名
            bizContent.put("payerAcctName", p_req1988.ownActName);
            // 机构批次号
            bizContent.put("batchNo", p_req1988.reqBatchNO);
            // 币种
            bizContent.put("currenoy", "CNY");
            // 异步通知
            bizContent.put("notifyURL", actItem.notifyURL);

            JSONArray detailJsonArray = new JSONArray();

            while(p_req1988.readRecord()) {
                JSONObject detailJSONObject = new JSONObject();
                // 机构订单号
                detailJSONObject.put("orderId", p_req1988.readedDetail.askNumber);
                // 收款银行行别
                detailJSONObject.put("bankType", p_req1988.readedDetail.recBankCode);
                // 收款银行支行名称
                detailJSONObject.put("bankName", p_req1988.readedDetail.recBankName + p_req1988.readedDetail.recBankLocation);
                // 收款银行支行号
                detailJSONObject.put("bankBranchNo", p_req1988.readedDetail.cnapsCode);
                // 收款方户名
                detailJSONObject.put("bankCardName", p_req1988.readedDetail.recName);
                // 收款方银行卡号
                detailJSONObject.put("bankCardNo", p_req1988.readedDetail.recAct);
                String cardType = "0";
                if ("1".equals(p_req1988.readedDetail.cardType)) {
                    cardType = "1";
                }
                // 收款方账号类型  0-卡 1-存折
                detailJSONObject.put("accountType", cardType);
                // 收款方对公对私账号类型 填默认值：2(对私)
                if ("1".equals(p_req1988.readedDetail.isPrivate)) {
                    detailJSONObject.put("pubPriv", "2");
                } else {
                    detailJSONObject.put("pubPriv", "1");
                }

                // 摘要
                String summary = p_req1988.readedDetail.memo;
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.purpose;
                }
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.useType;
                }
                if (StringHelper.isNullOrEmpty(summary)) {
                    summary = p_req1988.readedDetail.abstractATS;
                }
                detailJSONObject.put("optional", summary);

                // 交易金额
                detailJSONObject.put("amount", StringHelper.amountMultiply100(p_req1988.readedDetail.payAmount));

                detailJsonArray.add(detailJSONObject);
            }
            bizContent.put("details", detailJsonArray);
            ResponseDto responseDto = sendToSHIE(actItem, serviceCode, bizContent);
            // 解析银行返回
            String tmpRespCode = responseDto.getResponseCode();
            if ("0000".equals(tmpRespCode)) {
                JSONObject respBizContent = JSON.parseObject(responseDto.getBizContent());
                String msgCode = respBizContent.getString("msgCode");
                retAts.respCode = "0";
                retAts.respInfo = respBizContent.getString("msgInfo");
                retAts.transState = tmpRespCode + "+" + msgCode;
                retAts.payInfoCode = msgCode;
            } else {
                retAts.respCode = "0";
                retAts.transState = tmpRespCode;
                retAts.payInfoCode = tmpRespCode;
                retAts.respInfo = responseDto.getResponseDesc();
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }

        if(StringHelper.isNullOrEmpty(retAts.reqSeqID)){
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }

        retAts.writeRetToATS();
        return retAts;
    }

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        String commandCode = p_req1998.reqHeader.commandCode;
        if ("198803".equals(commandCode)) {
            return d_198803Qry(p_req1998);
        }else {
            return d_198801Qry(p_req1998);
        }
    }


    public RetAtsQryBatPayRec d_198801Qry(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.respCode = "";

        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1998.ownAct, "*");
            if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)){
                retAts.respCode = "-1";
                if(actItem == null){
                    retAts.respInfo = "未找到账号[" + p_req1998.ownAct + "]批量商户配置节点";
                }else{
                    retAts.respInfo = "账号[" + p_req1998.ownAct + "]证书文件不存在";
                }
                return retAts;
            }

            String serviceCode = SHIE01TransType.Q198801;

            Map<String, Object> bizContent = new HashMap<String, Object>();

            // 商户代码
            bizContent.put("comCode", actItem.inMerchantId);
            // 开始日期
            bizContent.put("startDate", Format.Date8Format.format(p_req1998.getBgnDateTime()));
            // 结束日期
            bizContent.put("endDate", Format.Date8Format.format(new Date()));
            // 批次号
            bizContent.put("batchNo", p_req1998.reqBatchNO);

            ResponseDto responseDto = sendToSHIE(actItem, serviceCode, bizContent);

            // 解析银行返回
            String tmpRespCode = responseDto.getResponseCode();
            if ("0000".equals(tmpRespCode)) {
                JSONObject respBizContent = JSON.parseObject(responseDto.getBizContent());

                String msgCode = respBizContent.getString("msgCode");
                if ("0000".equals(msgCode)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_req1998.reqBatchNO;

                    JSONArray respBodyJson = JSONArray.parseArray(respBizContent.getString("details"));
                    if(respBodyJson.size() > 0){
                        retAts.respInfo = respBizContent.getString("msgInfo");
                        retAts.transState = "";
                        retAts.payInfoCode = retAts.transState;

                        retAts.writeBeforeDetail();

                        for(int i = 0; i < respBodyJson.size(); i++){
                            JSONObject jsonDetail = respBodyJson.getJSONObject(i);
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                            tmpRetDetail.recAct = jsonDetail.getString("bankCardNo");
                            tmpRetDetail.recName = jsonDetail.getString("bankCardName");
                            tmpRetDetail.payAmount = StringHelper.amountDivide100(jsonDetail.getString("amount"));
                            tmpRetDetail.postScript = jsonDetail.getString("orderId");
                            tmpRetDetail.curType = jsonDetail.getString("currenoy");
                            tmpRetDetail.result = tmpRespCode + "+" + msgCode + "+" + jsonDetail.getString("payResult");
                            tmpRetDetail.payInfoCode = jsonDetail.getString("payResultMsg");
                            tmpRetDetail.memo = jsonDetail.getString("payResultMsg");
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.respInfo = respBizContent.getString("msgInfo") + "+交易明细为空";
                        retAts.transState = PaymentState.FAIL_Batch;
                        retAts.payInfoCode = msgCode + "+记录不存在";

                        retAts.writeBeforeDetail();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = respBizContent.getString("msgInfo");
                }
            } else {
                if ("9105".equals(tmpRespCode)) {
                    retAts.respCode = "0";
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = tmpRespCode;
                } else {
                    retAts.respCode = "-1";
                }

                retAts.respInfo = responseDto.getResponseDesc();
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }

        if(StringHelper.isNullOrEmpty(retAts.reqSeqID)){
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }

        retAts.writeAfterDetail();
        return retAts;
    }

    public RetAtsQryBatPayRec d_198803Qry(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.respCode = "";
        retAts.reqSeqID = p_req1998.reqBatchNO;
        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1998.ownAct, "*");
            if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)){
                retAts.respCode = "-1";
                if(actItem == null){
                    retAts.respInfo = "未找到账号[" + p_req1998.ownAct + "]批量商户配置节点";
                }else{
                    retAts.respInfo = "账号[" + p_req1998.ownAct + "]证书文件不存在";
                }
                return retAts;
            }

            boolean isNext = true;
            while (isNext) {
                String serviceCode = SHIE01TransType.Q198803;
                Map<String, Object> bizContent = new HashMap<String, Object>();
                bizContent.put("comCode", actItem.inMerchantId);
                /*机构订单号*/
                bizContent.put("batchNo", p_req1998.reqBatchNO);
                /*查询页数*/
                bizContent.put("pageNo", "1");
                ResponseDto responseDto = sendToSHIE(actItem, serviceCode, bizContent);
                // 解析银行返回
                String tmpRespCode = responseDto.getResponseCode();
                if ("0000".equals(tmpRespCode)) {
                    JSONObject respBizContent = JSON.parseObject(responseDto.getBizContent());
                    String msgCode = respBizContent.getString("msgCode");
                    String isNextStr = respBizContent.getString("hasNextPage");
                    if (isNextStr == null || "0".equals(isNextStr)) {
                        isNext = false;
                    }
                    if ("0000".equals(msgCode)) {
                        retAts.respCode = "0";
//                    retAts.reqSeqID = p_req1998.reqBatchNO;
                        JSONArray respBodyJson = JSONArray.parseArray(respBizContent.getString("details"));
                        if (respBodyJson != null && respBodyJson.size() > 0) {
                            retAts.respInfo = respBizContent.getString("msgInfo");
                            retAts.transState = "";
                            retAts.payInfoCode = retAts.transState;
                            retAts.writeBeforeDetail();
                            for (int i = 0; i < respBodyJson.size(); i++) {
                                JSONObject jsonDetail = respBodyJson.getJSONObject(i);
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payAmount = StringHelper.amountDivide100(jsonDetail.getString("amount"));
                                tmpRetDetail.postScript = jsonDetail.getString("orderId");
                                tmpRetDetail.result = tmpRespCode + "+" + msgCode + "+" + jsonDetail.getString("payResult");
                                tmpRetDetail.payInfoCode = jsonDetail.getString("payResultMsg");
                                tmpRetDetail.memo = jsonDetail.getString("payResultMsg");
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respInfo = respBizContent.getString("msgInfo") + "+交易明细为空";
                            retAts.transState = PaymentState.FAIL_Batch;
                            retAts.payInfoCode = msgCode + "+记录不存在";
                            retAts.writeBeforeDetail();
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respBizContent.getString("msgInfo");
                    }
                } else {
                    if ("9105".equals(tmpRespCode)) {
                        retAts.respCode = "0";
                        retAts.transState = PaymentState.FAIL_Batch;
                        retAts.payInfoCode = tmpRespCode;
                    } else {
                        retAts.respCode = "-1";
                    }

                    retAts.respInfo = responseDto.getResponseDesc();
                }
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }

        if(StringHelper.isNullOrEmpty(retAts.reqSeqID)){
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }

        retAts.writeAfterDetail();
        return retAts;
    }



    @Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return null;
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return null;
	}
}
